package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountLockVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplatel;
    @Qualifier("com.atguigu.tingshu.album.AlbumFeignClient")
    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public OrderInfoVo tradeOrderData(Long userId, TradeVo tradeVo) {

        OrderInfoVo orderInfoVo = new OrderInfoVo();
        orderInfoVo.setItemType(tradeVo.getItemType());

        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");

        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(tradeVo.getItemType())) {
            VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
            Assert.notNull(vipServiceConfig, "VIP套餐：{}不存在", tradeVo.getItemId());

            orderAmount = vipServiceConfig.getDiscountPrice();
            originalAmount = vipServiceConfig.getPrice();
            derateAmount = originalAmount.subtract(orderAmount);

            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(vipServiceConfig.getId());
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(vipServiceConfig.getPrice());
            orderDetailVoList.add(orderDetailVo);

            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateAmount(derateAmount);
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
            orderDerateVo.setRemarks("VIP限时优惠：" + derateAmount);

            orderDerateVoList.add(orderDerateVo);
        }else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())) {
            //3. 处理订单确认页数据-选择专辑
            Boolean isBuy = userFeignClient.isPaidAlbum(tradeVo.getItemId()).getData();
            if (isBuy){
                throw new GuiguException(400, "当前用户已购买该专辑！");
            }
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVoByUserId(userId).getData();
            Assert.notNull(userInfoVo, "用户信息不存在");
            Integer isVip = userInfoVo.getIsVip();
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(tradeVo.getItemId()).getData();
            Assert.notNull(albumInfo, "专辑信息不存在");
            originalAmount = albumInfo.getPrice();
            orderAmount = originalAmount;
            BigDecimal discount = albumInfo.getDiscount();
            if(discount.intValue() != -1){
                if(isVip.intValue() == 0){
                    orderAmount = originalAmount.multiply(discount)
                            .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
                if (isVip.intValue() == 1 && new Date().after(userInfoVo.getVipExpireTime())) {
                    //普通用户
                    orderAmount = originalAmount.multiply(discount)
                            .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            BigDecimal vipDiscount = albumInfo.getVipDiscount();
            if (vipDiscount.intValue() != -1) {
                if (isVip.intValue() == 1 && new Date().before(userInfoVo.getVipExpireTime())) {
                    //VIP会员用户
                    orderAmount = originalAmount.multiply(vipDiscount)
                            .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            derateAmount = originalAmount.subtract(orderAmount);

            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);

            if (derateAmount.doubleValue() > 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("专辑优惠："+derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())) {
            //4. 处理订单确认页数据-选择声音
            List<TrackInfo> waitBuyTrackInfoList = albumFeignClient.getWaitBuyTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount()).getData();
            if(CollectionUtil.isEmpty(waitBuyTrackInfoList)){
                throw new GuiguException(400, "无符合要求声音");
            }
            //4.2 远程调用"专辑服务"获取专辑信息（得到单集价格）
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(waitBuyTrackInfoList.get(0).getAlbumId()).getData();
            BigDecimal price = albumInfo.getPrice();

            //4.3 计算价格 数量*单价 声音没有折扣
            originalAmount = price.multiply(new BigDecimal(waitBuyTrackInfoList.size()));
            orderAmount = originalAmount;

            //4.4 遍历待购买声音列表封装订单明细列表
            orderDetailVoList= waitBuyTrackInfoList.stream()
                    .map(trackInfo -> {
                        OrderDetailVo orderDetailVo = new OrderDetailVo();
                        orderDetailVo.setItemId(trackInfo.getId());
                        orderDetailVo.setItemName(trackInfo.getTrackTitle());
                        orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                        orderDetailVo.setItemPrice(price);
                        return orderDetailVo;
                    }).collect(Collectors.toList());
        }
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);

        String key = RedisConstant.ORDER_TRADE_NO_PREFIX+userId;
        String tradeNo = IdUtil.fastUUID();

        redisTemplatel.opsForValue().set(key,tradeNo,5, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setTimestamp(DateUtil.current());
        //本次结算签名--防止数据篡改
        //将订单VO转为Map-将VO中支付方式null值去掉
        Map<String, Object> paramsMap = BeanUtil.beanToMap(orderInfoVo, false, true);
        //调用签名API对现有订单所有数据进行签名
        String sign = SignHelper.getSign(paramsMap);
        orderInfoVo.setSign(sign);

        //6.返回订单确认页数据VO对象
        return orderInfoVo;
    }

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Override
    public Map<String, String> submitOrder(OrderInfoVo orderInfoVo, Long userId) {
        //业务校验-验证流水号-解决订单重复提交问题
        String tradeNokey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //构建验证流水号lua脚本
        String scriptText = "if(redis.call('get', KEYS[1]) == ARGV[1]) then return redis.call('del', KEYS[1]) else return 0 end";
        //执行脚本
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Boolean.class);

        Boolean flag = (Boolean) redisTemplatel.execute(redisScript, Arrays.asList(tradeNokey), orderInfoVo.getTradeNo());
        if(!flag){
            throw new GuiguException(400, "流水号异常！");
        }

        Map<String, Object> mapParams = BeanUtil.beanToMap(orderInfoVo);
        mapParams.remove("payWay");
        SignHelper.checkSign(mapParams);
        OrderInfo orderInfo = this.saveOrderInfo(orderInfoVo,userId);
        if(SystemConstant.ORDER_PAY_ACCOUNT.equals(orderInfoVo.getPayWay())){
            // 4.1 TODO 余额支付-远程调用账户服务扣减账户余额
            AccountLockVo accountDeductVo = new AccountLockVo();
            accountDeductVo.setOrderNo(orderInfo.getOrderNo());
            accountDeductVo.setUserId(userId);
            accountDeductVo.setAmount(orderInfo.getOrderAmount());
            accountDeductVo.setContent(orderInfo.getOrderTitle());
            Result deductResult = accountFeignClient.checkAndDeduct(accountDeductVo);
            if (200 != deductResult.getCode()) {
                //扣减余额失败：全局事务都需要回滚
                throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
            }
            // 4.2 TODO 虚拟物品发货-远程调用用户服务新增购买记录
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
            userPaidRecordVo.setUserId(userId);
            userPaidRecordVo.setItemType(orderInfo.getItemType());
            List<Long> itemIdList = orderInfoVo.getOrderDetailVoList().stream().map(OrderDetailVo::getItemId).collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);

            Result paidRecordResult = userFeignClient.savePaidRecord(userPaidRecordVo);
            if (200 != paidRecordResult.getCode()) {
                //新增购买记录失败：全局事务都需要回滚
                throw new GuiguException(211, "新增购买记录异常");
            }
            // 4.3 订单状态：已支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.updateById(orderInfo);
        }
        //5.响应提交成功订单编号
        Map<String, String> mapResult = new HashMap<>();
        mapResult.put("orderNo", orderInfo.getOrderNo());
        return mapResult;
    }

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDerateMapper orderDerateMapper;
    /**
     * 保存订单及订单商品明细优惠明细
     * @param orderInfoVo
     * @param userId
     * @return
     */
    @Override
    public OrderInfo saveOrderInfo(OrderInfoVo orderInfoVo, Long userId) {
        OrderInfo orderInfo = BeanUtil.copyProperties(orderInfoVo, OrderInfo.class);
        orderInfo.setUserId(userId);
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        String orderNo = DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
        orderInfo.setOrderNo(orderNo);
        orderInfoMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();

        //2.保存订单商品明细
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        if (CollectionUtil.isNotEmpty(orderDetailVoList)) {
            orderDetailVoList.forEach(orderDetailVo -> {
                OrderDetail orderDetail = BeanUtil.copyProperties(orderDetailVo, OrderDetail.class);
                //关联订单ID
                orderDetail.setOrderId(orderId);
                orderDetailMapper.insert(orderDetail);
            });
        }

        //3.保存订单优惠明细
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if (CollectionUtil.isNotEmpty(orderDerateVoList)) {
            orderDerateVoList.forEach(orderDetailVo -> {
                OrderDerate orderDerate = BeanUtil.copyProperties(orderDetailVo, OrderDerate.class);
                //关联订单ID
                orderDerate.setOrderId(orderId);
                orderDerateMapper.insert(orderDerate);
            });
        }
        //4.返回订单对象
        return orderInfo;
    }

    @Override
    public OrderInfo getOrderInfo(Long userId, String orderNo) {
        //1.根据订单编号查询订单信息
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(queryWrapper);
        if(orderInfo!=null){
            //2.跟订单ID查询订单明细列表
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
            orderInfo.setOrderDetailList(orderDetailList);

            //3.跟订单ID查询订单优惠列表
            LambdaQueryWrapper<OrderDerate> orderDerateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDerateLambdaQueryWrapper.eq(OrderDerate::getOrderId, orderInfo.getId());
            List<OrderDerate> orderDerateList = orderDerateMapper.selectList(orderDerateLambdaQueryWrapper);
            orderInfo.setOrderDerateList(orderDerateList);

            //4.设置订单支付状态及支付方式：中文
            orderInfo.setOrderStatusName(this.getOrderStatusName(orderInfo.getOrderStatus()));
            orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));
            return orderInfo;
        }
        return null;
    }

    @Override
    public Page<OrderInfo> getUserOrderByPage(Page<OrderInfo> pageInfo, Long userId) {
        pageInfo =  orderInfoMapper.getUserOrderByPage(pageInfo,userId);
        pageInfo.getRecords().stream().forEach(orderInfo -> {
            //设置订单支付状态及支付方式：中文
            orderInfo.setOrderStatusName(this.getOrderStatusName(orderInfo.getOrderStatus()));
            orderInfo.setPayWayName(this.getPayWayName(orderInfo.getPayWay()));
        });
        return pageInfo;
    }

    private String getOrderStatusName(String orderStatus) {
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
            return "未支付";
        } else if (SystemConstant.ORDER_STATUS_PAID.equals(orderStatus)) {
            return "已支付";
        } else if (SystemConstant.ORDER_STATUS_CANCEL.equals(orderStatus)) {
            return "取消";
        }
        return null;
    }

    /**
     * 根据支付方式编号得到支付名称
     *
     * @param payWay
     * @return
     */
    private String getPayWayName(String payWay) {
        if (SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(payWay)) {
            return "微信";
        } else if (SystemConstant.ORDER_PAY_ACCOUNT.equals(payWay)) {
            return "余额";
        } else if (SystemConstant.ORDER_PAY_WAY_ALIPAY.equals(payWay)) {
            return "支付宝";
        }
        return "";
    }
}
